package com.sanq.product.books.controller;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.ChapterVo;
import com.sanq.product.books.entity.vo.PayHistoryVo;
import com.sanq.product.books.entity.vo.UsersVo;
import com.sanq.product.books.service.ChapterService;
import com.sanq.product.books.service.PayHistoryService;
import com.sanq.product.books.service.UsersService;
import com.sanq.product.books.utils.WebUtil;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.date.LocalDateUtils;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.security.annotation.IgnoreSecurity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@RestController
@RequestMapping("/app/chapter")
public class ChapterController {

    @Resource
    private ChapterService chapterService;
    @Resource
    private JedisPoolService jedisPoolService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private UsersService usersService;
    @Resource
    private PayHistoryService payHistoryService;

    @IgnoreSecurity
    @LogAnnotation(description = "通过bookId和chapterId查询内容")
    @GetMapping(value = "/findChapterContentByBookIdAndChapter")
    public Response getById(HttpServletRequest request, Long booksId, Long chapterId) {
        ChapterVo chapterVo = chapterService.findChapterContentByBookIdAndChapter(booksId, chapterId);

        if (null == chapterVo)
            return new Response().failure("暂无当前章节");

        //下一章
        chapterVo.setNextChapterId(chapterService.findNextChapter(booksId, chapterId));
        //上一章
        chapterVo.setLastChapterId(chapterService.findPrevChapter(booksId, chapterId));

        // 获取用户
        String token = Redis.ReplaceKey.getTokenUser(WebUtil.getToken(request));
        UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(token), UsersVo.class);


        if (chapterVo.getCostGold().intValue() > 0 && null == usersVo) {
            chapterVo.setChapterContentVo(null);
            return new Response().success(chapterVo);
        }


        //免费章节
        if (chapterVo.getCostGold().intValue() == 0)
            return new Response().success(chapterVo);


        //该章节是否已经付费
        PayHistoryVo payHistoryVo = new PayHistoryVo();
        payHistoryVo.setUserId(usersVo.getId());
        payHistoryVo.setBookId(booksId);
        payHistoryVo.setChapterId(chapterId);

        int count = payHistoryService.findCount(payHistoryVo);

        if (count > 0)
            return new Response().success(chapterVo);

        //判断用户是否为会员
        if (usersVo.getVipEndTime().getTime() > LocalDateUtils.nowTime().getTime())
            return new Response().success(chapterVo);

        //不是会员 判断金币是否足够
        BigDecimal sub = usersVo.getGold().subtract(chapterVo.getCostGold());
        if (sub.intValue() >= 0) {
            //会员减少金币
            taskExecutor.execute(() -> {
                //减少金币
                usersVo.setGold(sub);
                usersService.update(usersVo, usersVo.getId());

                jedisPoolService.set(token, JsonUtil.obj2Json(usersVo));
            });
            taskExecutor.execute(() -> {
                //加入消费记录
                payHistoryVo.setPayPrice(chapterVo.getCostGold());
                payHistoryService.save(payHistoryVo);
            });
            return new Response().success(chapterVo);
        }

        chapterVo.setChapterContentVo(null);

        return new Response().success(chapterVo);
    }

    @IgnoreSecurity
    @LogAnnotation(description = "分页查询数据")
    @GetMapping(value = "/list")
    public Response findListByPager(HttpServletRequest request, ChapterVo chapterVo, Pagination pagination) {

        Pager<ChapterVo> pager = chapterService.findListByPage(chapterVo, pagination);

        return pager != null ? new Response().success(pager) : new Response().failure();
    }

    @IgnoreSecurity
    @LogAnnotation(description = "根据bookId查询最新章节和总章节数")
    @GetMapping(value = "/findTotalByBookId")
    public Response findTotalByBookId(HttpServletRequest request, Long bookId) {

        ChapterVo chapterVo = chapterService.findTotalByBookId(bookId);

        return chapterVo != null ? new Response().success(chapterVo) : new Response().failure();
    }
}